import java.io.IOException;
import java.io.InputStream;

/**
 * @author wcj
 * @Date 2021/6/3 16:19
 * @Version 1.0
 */
public class ClassLoaderTest {

    /**
     * 判定两个类是不是相同的，不仅需要这两个类本身相同，同时还需要加载这两个类的类加载器相同
     * 只有类加载器和类都相同，我们才能确保两个类是相同的
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        ClassLoader myLoader = new ClassLoader() {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                try {
                    String filename = name.substring(name.lastIndexOf(".") + 1) + ".class";
                    InputStream is = this.getClass().getResourceAsStream(filename);
                    if (is == null) {
                        return super.loadClass(name);
                    }
                    byte[] bytes = new byte[is.available()];
                    is.read(bytes);
                    return defineClass(name, bytes, 0, bytes.length);
                } catch (IOException e) {
                    throw new RuntimeException(name);
                }
            }
        };

        Object obj = myLoader.loadClass("org.fenixsoft.classloading.ClassLoaderTest").newInstance();
        System.out.println(obj.getClass());
    }
}
